import axios from 'axios'
import store from '../store'

const request = axios.create({
  baseURL: '',
  timeout: 15000
})

// 请求拦截
request.interceptors.request.use(config => {
  localStorage.getItem('token') ? config.headers.token = localStorage.getItem('token') : ''
  config.cancelToken = new axios.CancelToken(cancel => store.commit('addHttpRequestList', cancel))
  return config
}, err => {
  err.response = { code: 500, msg:'请求失败，请检查网络' }
  return err.response
})

// 响应拦截
request.interceptors.response.use(response => {
  return response.data
}, err => {
  if(err.message === 'suspend') {
    return new Promise(() => {})
  }else if (err.message.indexOf('timeout') !== -1) {
    err.response = { code: 500, msg:'响应超时，请检查网络' }
    return err.response
  }
  return Promise.reject(err)
})

export default request